package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.BaseEnum.StateEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.entity.Company;
import com.joint.base.entity.LocationEntity;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Locations;
import com.joint.base.service.LocationEntityService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.ProInfo;
import com.joint.core.entity.ProSignIn;
import com.joint.core.service.ProInfoService;
import com.joint.core.service.ProSignInService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * Created by xh on 2015/3/2.
 */
@ParentPackage("com")
public class AjaxProSigninAction extends BaseAdminAction {

    @Resource
    private ProSignInService proSignInService;
    @Resource
    private ProInfoService proInfoService;
    @Resource
    private UsersService usersService;
    @Resource
    private LocationEntityService locationEntityService;

    protected ProSignIn proSignIn;

    private String keyId;
    private String proInfoId;

    private String address;
    private int status;
    private String start;
    private String end;
    private String userId;
    private List<Users> usersList;

    private Set<Users> usersSet;
    private Set<ProInfo> proInfoSet;
    private List<ProInfo> proInfoList;

    private String proArea;

    public String list(){

        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        Company com = usersService.getCompanyByUser();
        Users users=usersService.getLoginInfo();
        Map<String,Object> params=Maps.newHashMap();
        params.put("state",new StateEnum[]{StateEnum.Enable});

        pager = proSignInService.findByPagerAndLimit(pager,users,com,params);
        //pager=proSignInService.findByPagerAndCompany(pager,null,com,params);
        List<ProSignIn> proSignInList = (List<ProSignIn>)(pager.getTotalCount()>0?pager.getList(): Lists.newArrayList());

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(ProSignIn proSignIn:proSignInList){

            rMap = new HashMap<String, Object>();
            rMap.put("id",proSignIn.getId());
            rMap.put("proname", proSignIn.getProInfo().getName());
            ProInfo proInfo = proSignIn.getProInfo();
            rMap.put("proArea", proInfo.getProvince()+proInfo.getCity()+proInfo.getCounty());
            rMap.put("proAddress", proInfo.getAddress());
            rMap.put("createDate", DataUtil.DateToString(proSignIn.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("address",proSignIn.getAddress());
            rMap.put("creater",proSignIn.getCreater().getName());
            rMap.put("status", proSignIn.getStatus());

            dataRows.add(JSONObject.fromObject(rMap));
        }
        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String listMap() throws ParseException {
        pager = new Pager();
        pager.setPageSize(rows);
        pager.setPageNumber(page);

        Company com = usersService.getCompanyByUser();
        Map rmap = Maps.newHashMap();

        rmap.put("state",StateEnum.Enable);
        if(StringUtils.isNotEmpty(userId)){
            rmap.put("creater.id",userId);
        }

        if(StringUtils.isNotEmpty(proInfoId)){
            rmap.put("proInfo.id",proInfoId);
        }
        pager=proSignInService.findByPagerAndCompany(pager,null,com,rmap);
        if(StringUtils.isNotEmpty(start) || StringUtils.isNotEmpty(end)){
            Date endDate = DataUtil.getAfterDay(DataUtil.StringToDate(end, "yyyy-MM-dd"), 1);
            pager=proSignInService.findByPagerAndCompany(pager,"createDate", DataUtil.StringToDate(start, "yyyy-MM-dd"),endDate,null,com,rmap);
        }


        if(StringUtils.isEmpty(start) && StringUtils.isEmpty(end) && StringUtils.isEmpty(userId)
            && StringUtils.isEmpty(proInfoId)){
            pager=new Pager();
        }
        List<ProSignIn> proSignInList = (List<ProSignIn>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        for(ProSignIn proSign:proSignInList){
            Map<String,Object> pMap = Maps.newHashMap();
            pMap.put("id",proSign.getId());
            pMap.put("username",proSign.getCreater().getName());
            pMap.put("proInfoname",proSign.getProInfo().getName());
            pMap.put("time", DataUtil.DateTimeToString(proSign.getCreateDate()));
            if(StringUtils.isNotEmpty(proSign.getLocationId())){
                Locations locations = locationsService.get(proSign.getLocationId());
                LocationEntity locationEntity=null;
                if(locations!=null){
                   locationEntity=locationEntityService.getLocationByTargetId(locations.getId());
                }else{
                    continue;
                }
                if(locationEntity!=null){
                    pMap.put("longitude", locationEntity.getLongitude());
                    pMap.put("latitude", locationEntity.getLatitude());
                    pMap.put("address",locationsService.getAddress(locations));
                }else{
                    pMap.put("longitude",locations.getLongitude());
                    pMap.put("latitude", locations.getLatitude());
                    pMap.put("address",proSign.getAddress());
                }

            }

            if (proSign.getStatus()==1){
                pMap.put("status", "正常");
            }else{
                pMap.put("status", "迟到");
            }
            dataRows.add(JSONObject.fromObject(pMap));
        }

        data.put("dataRows",dataRows);
        data.put("total",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String view(){
        return "view";
    }

    public String calendar(){
        return "calendar";
    }

    public String read(){
        //LogUtil.info("keyId:" + keyId);
        if(StringUtils.isNotEmpty(keyId)){
            proSignIn = proSignInService.get(keyId);
        }
        ProInfo proInfo = proSignIn.getProInfo();
        proArea = proInfo.getProvince()+proInfo.getCity()+proInfo.getCounty();
        Locations locations=locationsService.get(proSignIn.getLocationId());
        LocationEntity locationEntity=locationEntityService.getLocationByTargetId(locations.getId());
        if(locationEntity!=null){
            address=locationsService.getAddress(locations);
        }else{
            address=proSignIn.getAddress();
        }
        return "read";
    }

    public String input(){
        ProInfo proInfo;
        if (StringUtils.isNotEmpty(proInfoId)){
            proInfo = proInfoService.get(proInfoId);
        }else {
            return ajaxHtmlCallback("404", "所属项目信息表丢失！","操作状态");
        }

        if (StringUtils.isNotEmpty(keyId)){
            proSignIn = proSignInService.get(keyId);
        }else{
            proSignIn = new ProSignIn();
            proSignIn.setProInfo(proInfo);
        }
        proArea = proInfo.getProvince()+proInfo.getCity()+proInfo.getCounty();
        return  "input";
    }


    public String save(){
        //LogUtil.info("keyId:"+keyId);
        if(StringUtils.isNotEmpty(keyId)){
            proSignIn = proSignInService.get(keyId);
        }else{
            proSignIn = new ProSignIn();
        }

        if (StringUtils.isNotEmpty(proInfoId)){
            ProInfo proInfo = proInfoService.get(proInfoId);
            proSignIn.setProInfo(proInfo);
            proSignIn.setName(proInfo.getName());
        }

        proSignIn.setAddress(address);
        proSignIn.setStatus(status);

        proSignIn.setCreater(usersService.getLoginInfo());
        proSignIn.setCompany(usersService.getCompanyByUser());
        proSignInService.updateAndEnable(proSignIn);
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    public String delete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("404", "请选择客户信息！","操作状态");
        }
        ProSignIn proSignIn = proSignInService.get(keyId);
        proSignIn.setState(StateEnum.Delete);
        proSignInService.update(proSignIn);
        return ajaxHtmlCallback("200", "删除成功！","操作状态");
    }


    public String map(){
        Users users=usersService.getLoginInfo();
        Company company=usersService.getCompanyByUser();
        Map<String,Object> rmap=Maps.newHashMap();
        rmap.put("state",StateEnum.Enable);
        usersSet= Sets.newHashSet();
        proInfoSet=Sets.newHashSet();
        pager= usersService.findByPagerAndCompany(new Pager(0),null,company,new StateEnum[]{StateEnum.Enable});
        usersList= (List<Users>) pager.getList();
        usersSet.addAll(usersList);
        pager=proInfoService.findByPagerAndLimit(new Pager(0),users,company,rmap);
        proInfoList= (List<ProInfo>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
        proInfoSet.addAll(proInfoList);
        return "map";
    }


    @Override
    public String getKeyId() {
        return keyId;
    }

    @Override
    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    public String getProInfoId() {
        return proInfoId;
    }

    public void setProInfoId(String proInfoId) {
        this.proInfoId = proInfoId;
    }

    public ProSignIn getProSignIn() {
        return proSignIn;
    }

    public void setProSignIn(ProSignIn proSignIn) {
        this.proSignIn = proSignIn;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getProArea() {
        return proArea;
    }

    public void setProArea(String proArea) {
        this.proArea = proArea;
    }

    public String getStart() {
        return start;
    }

    public void setStart(String start) {
        this.start = start;
    }

    public String getEnd() {
        return end;
    }

    public void setEnd(String end) {
        this.end = end;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public List<Users> getUsersList() {
        return usersList;
    }

    public void setUsersList(List<Users> usersList) {
        this.usersList = usersList;
    }

    public List<ProInfo> getProInfoList() {
        return proInfoList;
    }

    public void setProInfoList(List<ProInfo> proInfoList) {
        this.proInfoList = proInfoList;
    }

    public Set<ProInfo> getProInfoSet() {
        return proInfoSet;
    }

    public void setProInfoSet(Set<ProInfo> proInfoSet) {
        this.proInfoSet = proInfoSet;
    }

    public Set<Users> getUsersSet() {
        return usersSet;
    }

    public void setUsersSet(Set<Users> usersSet) {
        this.usersSet = usersSet;
    }


}
